<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.race后台请求超时处理</title>
</head>
<body>
  
</body>
<script src="./ajax处理异步请求任务/ajax.js"></script>
<script>
    //promise.race() 处理多个promise但哪个返回的快我就用哪个
    // const p1 = new Promise((resolve, reject) => {
    //     setTimeout(() =>{
    //          resolve('promise p2')
    //      }, 3000);
    // });

    // const p2 = new Promise((resolve, reject) => {
    //      setTimeout(() =>{
    //          resolve('promise p2')
    //      }, 2000);
    // });
    
    // Promise.race([p1, p2]).then(results => {
    //     console.log(results); //返回更快的
    // });

    
    function query(url, delay=100){
        let promises = [
        ajax(url),
        new Promise((resolve, reject) => {
            setTimeout(() => {
                //只要请求超过两秒钟还没有给我返回学生数据则采用下面的promise即认为你请求超时
                reject('请求超时');
            }, delay);
        }),
      ]
      return Promise.race(promises);
    }
    

    query(`http://localhost:5002/api/students/${1}`)
         .then(value => console.log(value))
         .catch(err => console.log(err));
     
</script>
</html>